package utils

/*
*

	输出平均值
*/
type ListAvg struct {
	lst       []float64
	currV     float64
	MaxN      int
	restflag  byte
	OnValFunc func(v float64)
}

func NewListAvg(maxN int) *ListAvg {
	v := &ListAvg{
		MaxN:     maxN,
		restflag: 1,
	}
	return v
}

func (this *ListAvg) CurrentVal() (v float64) {
	return this.currV
}

func (this *ListAvg) Count() int {
	return len(this.lst)
}

/*
**

	可以多次配置,中途配置
*/
func (this *ListAvg) ConfigAvgN(v int) *ListAvg {
	this.MaxN = v
	return this
}

func (this *ListAvg) Push(v float64) int {
	if this.restflag == 1 {
		this.lst = make([]float64, 0, this.MaxN)
		this.restflag = 0
	}
	this.lst = append(this.lst, v)

	if len(this.lst) >= this.MaxN {
		var total float64 = 0
		for i := 0; i < len(this.lst); i++ {
			total += this.lst[i]
		}

		this.currV = total / float64(len(this.lst))

		if this.OnValFunc != nil {
			this.OnValFunc(this.currV)
		}

		this.restflag = 1

		//this.lst = make([]float64, 0, this.MaxN)
		return 1
	}
	return 0
}
